package com.juzhi.dvrapp.activity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;

import com.juzhi.dvrapp.R;
import com.juzhi.dvrapp.bean.Device;
import com.juzhi.dvrapp.bean.DeviceUser;
import com.juzhi.dvrapp.callback.DialogCallback;
import com.juzhi.dvrapp.callback.JsonCallback;
import com.juzhi.dvrapp.bean.LzyResponse;
import com.juzhi.dvrapp.bean.SimpleResponse;
import com.juzhi.dvrapp.manager.DeviceManager;
import com.juzhi.dvrapp.utils.Config;
import com.juzhi.dvrapp.utils.Convert;
import com.juzhi.dvrapp.utils.MLog;
import com.juzhi.dvrapp.utils.T;
import com.juzhi.dvrapp.utils.Urls;
import com.juzhi.dvrapp.utils.ValidatorUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mcxtzhang.commonadapter.lvgv.CommonAdapter;
import com.mcxtzhang.commonadapter.lvgv.ViewHolder;

import java.util.List;

import butterknife.OnClick;

/**
 * The type Device user activity.
 */
public class DeviceUserActivity extends BaseAcitivity {


    private Device device;
    private AlertDialog alertDialog;
    private EditText account;
    private String mEmail;
    private String ssid;

    @Override
    public int getLayoutId() {
        return R.layout.activity_device_user;
    }

    @Override
    protected void initView() {
        initHeaderView();
        hideFunction();
        setTitleText(getResources().getString(R.string.setting_user));

        if (getSavedInstanceState()!=null){
            ssid = getSavedInstanceState().getString(Config.SSID);
        }else
            ssid = getIntent().getStringExtra(Config.SSID);
        if (ssid !=null) {
            DeviceManager deviceManager = DeviceManager.getDeviceManager(this);
            device = deviceManager.getDevice(ssid);
            getEmailHttp();
        }else {
            finish();
        }

    }

    private void getEmailHttp() {
        OkGo.<LzyResponse<String>>get(Urls.URL_GETEMAIL)
                .tag(DeviceUserActivity.this)
                .params(Config.ID, device.getUserId())
                .execute(new JsonCallback<LzyResponse<String>>() {
                    @Override
                    public void onSuccess(Response<LzyResponse<String>> response) {
                        if (response.body().status == Config.DEVICE_RESULT_SUCCESS) {
                            mEmail = response.body().result;
                            MLog.w(mEmail);
                            if (account != null) {
                                account.setText(response.body().result);
                            }
                        }

                    }
                });
    }


    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        outState.putString(Config.SSID,ssid);
    }

    /**
     * On view clicked.
     *
     * @param view the view
     */
    @OnClick({R.id.activity_user_device_edit, R.id.activity_user_device_add, R.id.activity_user_device_del, R.id.activity_user_device_email})
    public void onViewClicked(View view) {
        closeDialog();
        switch (view.getId()) {
            case R.id.activity_user_device_edit:
                showUserEdit();
                break;
            case R.id.activity_user_device_email:
                showUserEmail();
                break;
            case R.id.activity_user_device_add:
                if (device.getSystemLevel() == 0)
                    showUserAdd();
                else
                    T.showShort(getResources().getString(R.string.set_right));
                break;
            case R.id.activity_user_device_del:
                if (device.getSystemLevel() == 0)
                    getUsersHttp();
                else
                    T.showShort(getResources().getString(R.string.set_right));
                break;
        }
    }

    private void getUsersHttp() {
        OkGo.<LzyResponse<List<DeviceUser>>>get(Urls.URL_GETUSERS)
                .tag(DeviceUserActivity.this)
                .params(Config.SSID, device.getDeviceModel().getSsid())
                .execute(new DialogCallback<LzyResponse<List<DeviceUser>>>(DeviceUserActivity.this) {
                    @Override
                    public void onSuccess(Response<LzyResponse<List<DeviceUser>>> response) {
                        if (response.body().status == Config.DEVICE_RESULT_SUCCESS) {
                            showUserDel(response.body().result);
                        }
                    }
                });
    }


    private void showUserEdit() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle(getResources().getString(R.string.string_change_password));
        View view = View.inflate(this, R.layout.dialog_user_edit, null);
        final TextInputLayout nameLayout = (TextInputLayout) view.findViewById(R.id.dialog_edit_device_name);
        final TextInputLayout passwordLayout = (TextInputLayout) view.findViewById(R.id.dialog_edit_device_password);
        EditText name = nameLayout.getEditText();
        final EditText password = passwordLayout.getEditText();
        password.setFocusable(true);
        password.setFocusableInTouchMode(true);
        password.requestFocus();
        name.setText(device.getDeviceModel().getUserName());
        password.setText(device.getDeviceModel().getPassword());
        dialog.setView(view);
        dialog.setPositiveButton(getResources().getString(R.string.string_ok), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                OkGo.<LzyResponse<Void>>post(Urls.URL_DEVICEUSERRESETSELF)
                        .tag(DeviceUserActivity.this)
                        .params(Config.ID, device.getUserId())
                        .params(Config.SSID, device.getDeviceModel().getSsid())
                        .params(Config.USERNAME, device.getDeviceModel().getUserName())
                        .params(Config.PASSWORD, password.getText().toString().trim())
                        .execute(new DialogCallback<LzyResponse<Void>>(DeviceUserActivity.this) {
                            @Override
                            public void onSuccess(Response<LzyResponse<Void>> response) {
                                if (response.body().status == Config.DEVICE_RESULT_SUCCESS) {
                                    device.alterPwd(password.getText().toString().trim());
                                    MLog.w(device.getDeviceModel().getPassword());
                                    T.showShort(getResources().getString(R.string.string_change_password_succeed));
                                }
                            }
                        });
            }
        });
        dialog.setNegativeButton(getResources().getString(R.string.string_cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                closeKeyboard();
            }
        });
        alertDialog = dialog.create();
        alertDialog.getWindow().setWindowAnimations(com.bigkoo.pickerview.R.style.pickerview_dialogAnim);
        alertDialog.getWindow().setBackgroundDrawableResource(R.drawable.loading_bg);
        alertDialog.show();
    }

    private void showUserEmail() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle(getResources().getString(R.string.string_device_user_email));
        View view = View.inflate(this, R.layout.dialog_user_email, null);
        final TextInputLayout accountLayout = (TextInputLayout) view.findViewById(R.id.dialog_email_device_account);
        account = accountLayout.getEditText();
        account.setText(mEmail);
        account.setFocusable(true);
        account.setFocusableInTouchMode(true);
        account.requestFocus();
        dialog.setView(view);
        dialog.setPositiveButton(getResources().getString(R.string.string_ok), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String accountStr = account.getText().toString();
                if (ValidatorUtils.isEmail(accountStr)) {
                    closeKeyboard();
                    if (accountStr.equals(mEmail)) {
                        T.showShort(getResources().getString(R.string.string_device_newemail_error));
                    }
                    //将邮箱地址发送给服务器
                    OkGo.<SimpleResponse>post(Urls.URL_SETEMAIL)
                            .tag(DeviceUserActivity.this)
                            .params(Config.ID, device.getUserId())
                            .params(Config.EMAIL, accountStr)
                            .execute(new JsonCallback<SimpleResponse>() {
                                @Override
                                public void onSuccess(Response<SimpleResponse> response) {
                                    if (response.body().status == Config.DEVICE_RESULT_SUCCESS)
                                        T.showShort(getResources().getString(R.string.string_setting_succeed));
                                    else
                                        T.showShort(getResources().getString(R.string.string_setting_error));
                                }

                            });
                } else {
                    T.showShort(getResources().getString(R.string.string_device_email_error));
                }


            }
        });
        dialog.setNegativeButton(getResources().getString(R.string.string_cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                closeKeyboard();
            }
        });
        alertDialog = dialog.create();
        alertDialog.getWindow().setWindowAnimations(com.bigkoo.pickerview.R.style.pickerview_dialogAnim);
        alertDialog.getWindow().setBackgroundDrawableResource(R.drawable.loading_bg);
        alertDialog.show();
    }

    private void showUserAdd() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle(getResources().getString(R.string.string_device_user_add));
        View view = View.inflate(this, R.layout.dialog_user_add, null);
        final TextInputLayout nameLayout = (TextInputLayout) view.findViewById(R.id.dialog_add_device_name);
        final TextInputLayout passwordLayout = (TextInputLayout) view.findViewById(R.id.dialog_add_device_password);
        final RadioButton adminRadio = (RadioButton) view.findViewById(R.id.dialog_add_device_type_admin);
        final EditText nameEt = nameLayout.getEditText();
        final EditText passwordEt = passwordLayout.getEditText();
        dialog.setView(view);
        dialog.setPositiveButton(getResources().getString(R.string.string_ok), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String name = nameEt.getText().toString().trim();
                String pwd = passwordEt.getText().toString().trim();
                if (ValidatorUtils.isSpechars(name) || ValidatorUtils.isSpechars(pwd)) {
                    T.showShort(getResources().getString(R.string.user_pwd_no_show));
                } else if (TextUtils.isEmpty(pwd)) {
                    T.showShort(getResources().getString(R.string.input_camera_password));
                } else {
                    int type = adminRadio.isChecked() ? 0 : 1;
                    OkGo.<SimpleResponse>post(Urls.URL_INSERTUSER)
                            .tag(DeviceUserActivity.this)
                            .params("param", Convert.toJson(new DeviceUser(device.getDeviceModel().getSsid(), name, pwd, type)))
                            .execute(new JsonCallback<SimpleResponse>() {
                                @Override
                                public void onSuccess(Response<SimpleResponse> response) {
                                    if (response.body().status == Config.DEVICE_RESULT_SUCCESS)
                                        T.showShort(getResources().getString(R.string.string_device_user_add_succeed));
                                    else
                                        T.showShort(getResources().getString(R.string.string_device_user_add_error));
                                }
                            });
                }
            }
        });
        dialog.setNegativeButton(getResources().getString(R.string.string_cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                closeKeyboard();
            }
        });
        alertDialog = dialog.create();
        alertDialog.getWindow().setWindowAnimations(com.bigkoo.pickerview.R.style.pickerview_dialogAnim);
        alertDialog.getWindow().setBackgroundDrawableResource(R.drawable.loading_bg);
        alertDialog.show();
    }

    private void showUserDel(final List<DeviceUser> result) {
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle(getResources().getString(R.string.string_device_user_del));
        dialog.setPositiveButton(getResources().getString(R.string.string_ok), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        dialog.setNegativeButton(getResources().getString(R.string.string_cancel), null);
        dialog.setAdapter(new CommonAdapter<DeviceUser>(DeviceUserActivity.this, result, R.layout.dialog_user_del_item) {
            @Override
            public void convert(ViewHolder viewHolder, final DeviceUser deviceUser, int i) {
                viewHolder.setText(R.id.dialog_del_device_name, deviceUser.getUsername());
                viewHolder.setText(R.id.dialog_del_device_type, deviceUser.getType() == 0 ? getResources().getString(R.string.string_admin) : getResources().getString(R.string.string_guest));
                viewHolder.setOnClickListener(R.id.dialog_del_device_delBtn, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (deviceUser.getUsername().equals(device.getDeviceModel().getUserName()))
                            T.showShort(getString(R.string.string_device_user_del));
                        else {
                            OkGo.<SimpleResponse>post(Urls.URL_DELUSER)
                                    .tag(DeviceUserActivity.this)
                                    .params(Config.ID, deviceUser.getId())
                                    .execute(new JsonCallback<SimpleResponse>() {
                                        @Override
                                        public void onSuccess(Response<SimpleResponse> response) {
                                            if (response.body().status == Config.DEVICE_RESULT_SUCCESS) {
                                                T.showShort(getResources().getString(R.string.string_del_succeed));
                                                result.remove(deviceUser);
                                                notifyDataSetChanged();
                                            } else {
                                                T.showShort(getResources().getString(R.string.string_del_error));
                                            }

                                        }
                                    });
                        }
                    }
                });
            }
        }, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        alertDialog = dialog.create();
        alertDialog.getWindow().setWindowAnimations(com.bigkoo.pickerview.R.style.pickerview_dialogAnim);
        alertDialog.getWindow().setBackgroundDrawableResource(R.drawable.loading_bg);
        alertDialog.show();
    }


    private void closeDialog() {
        if (alertDialog != null) {
            if (alertDialog.isShowing())
                alertDialog.dismiss();
        }
        alertDialog = null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        closeDialog();
    }
}
